package com.wanter.users.controller;

import com.wanter.common.utils.json.JsonUtil;
import com.wanter.common.utils.result.ReturnMap;
import com.wanter.common.utils.web.WebStatusUtils;
import com.wanter.users.entity.User;
import com.wanter.users.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 用户操作的控制层
 */
@Controller
@RequestMapping("/userAction/")
public class UserController {
    @Resource
    private UserService userService;
    private final Logger logger = Logger.getLogger(this.getClass());


    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回结果集
     */
    @RequestMapping(method = RequestMethod.POST, value = "login")
    @ResponseBody
    public ReturnMap login(String username, String password) {
        ReturnMap returnMap = new ReturnMap();
        returnMap.setSuccess(false);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            logger.info("用户名或密码为空!");
            returnMap.setMessage("请输入用户名或者密码!!");
        }

        User user = userService.login(username, password);
        if (user != null) {
            returnMap.setSuccess(true);
            returnMap.setMessage("登录成功");
        } else {
            returnMap.setMessage("用户名或密码不对");
        }
        if (logger.isDebugEnabled()){
            logger.debug(JsonUtil.objectToJson(returnMap));
        }
        return returnMap;
    }

    /**
     * 注册用户
     *
     * @param user 用户信息
     * @return 返回结果集
     */
    @RequestMapping(method = RequestMethod.POST, value = "register")
    @ResponseBody
    public ReturnMap registerUser(User user) {
        ReturnMap returnMap = new ReturnMap();
        int flag = userService.insertRegister(user);
        if (flag > 1) {
            returnMap.setMessage("注册成功");
        } else {
            returnMap.setMessage("注册失败,用户名已被使用");
            returnMap.setSuccess(false);
        }
        return returnMap;
    }

    /**
     * 修改用户密码
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回结果集
     */
    @RequestMapping(method = RequestMethod.POST, value = "updatePassword")
    @ResponseBody
    public ReturnMap updatePassword(String username, String password) {
        ReturnMap returnMap = new ReturnMap();
        userService.updatePassword(username, password);
        returnMap.setMessage("修改密码成功");
        return returnMap;
    }


}
